package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;

//拦截器
@Slf4j
@Component
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;
    /**
     * 拦截器
     * 在执行controller之前进行拦截校验
     * 先获取请求投中的cookie,然后再从session中获取对应的用户信息，在判断用户是否存在，存在保存用户到ThreadLocal中，方便后续使用!放心
     *                                                                    如果用户不存在!则返回错误信息
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取session
        //TODO:1。获取请求头中的authorzation
        String authorization = request.getHeader("authorization");

        //判段token存
        if (authorization == null) {
            log.info("Token判段");
            return true;
        }
        //2.获取session中的用户信息
        //ToDO:2.优化从Redis中获取用户信息
//        Object user = session.getAttribute("user");
        Map<Object, Object> entries = stringRedisTemplate.opsForHash().entries(LOGIN_USER_KEY + authorization);

        //判段用户是否存在
        if (entries.isEmpty()) { // 用户不存在
            log.info("用户判段");
            return true;
        }
        //将Hash转换成DTO
        UserDTO userDTO1 = BeanUtil.fillBeanWithMap(entries, new UserDTO(), true);
//        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        //存在，将用户信息保存到ThreadLocal中
        log.info("将用户数据放置到线程池中");
        UserHolder.saveUser(userDTO1);
        //TODO:刷新Token有效期
        stringRedisTemplate.expire(LOGIN_USER_KEY + authorization, RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES); //30分钟
        log.info("刷新Token");
        //放行
        return true;

//        UserHolder.saveUser((UserDTO) user);

    }


    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
}
